// new-expense 优化
// 思路：拆分6个大组件， 采用React.createElement()避免界面太多的jsx

import React, { Component, PropTypes } from 'react';
import { Spin } from 'antd';
import { connect } from 'react-redux';
import { expenseArea } from './data-source';
import handleForm from './handle-form';

@connect(mapStateToProps)
@handleForm
class CreateExpense extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      typesMap: new Map(expenseArea),
      typesObj: {
        'expenseType': { func: this.handleExpenseType },
        'invoice': {},
        'businessCard': {},
        'invoiceOCR': {},
        'invoiceDisabledEdit': {},
        'expenseForm': {},
      },
      currentType: this.props.sourcesType,
    };
  }


  componentWillMount() {
    this.handleInit()
      .then();
  }

  handleInit = async () => {
    const { typesObj, currentType } = this.state;
    try {
      await typesObj[currentType].func();
    }
    catch (e) {
    }
  };

  handleSelectExpenseType = (expenseType) => {
    this.setState({ expenseType, currentType: 'expenseForm' });
  };

  handleExpenseType = () => {
    const { typesMap, expenseType } = this.state;
    const { user: { userOID } } = this.props;
    const content = typesMap.get('expenseType');
    return new Promise(resolve => {
      content.params = {
        source: 'custom',
        showMessageInfo: true,
        param: { userOID },
        onSelect: this.handleSelectExpenseType,
        value: expenseType
      };
      this.setState({ typesMap }, () => {resolve(true);});
    });
  };

  renderArea = () => {
    const { typesMap, currentType } = this.state;
    return React.createElement(typesMap.get(currentType).component, typesMap.get(currentType).params);
  };

  render() {
    const { loading } = this.state;
    return (
      <Spin spinning={loading}>
        <section className="create-expense">
          {this.renderArea()}
        </section>
      </Spin>
    );
  }

  static propTypes = {
    sourcesType: PropTypes.string,
  };

  static defaultProps = {
    sourcesType: 'expenseType',
  };
}

function mapStateToProps(state) {
  return {
    user: state.login.user,
  };
}

export default CreateExpense;

